<template>
  <div class="user-manage-view">
    <el-container>
      <el-header style="text-align: center; font-size: 20px; height: 50px; line-height: 50px;">
        用户管理
      </el-header>

      <el-main style="padding: 0;">
        <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px;">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          <div style="display: flex; align-items: center;">
            <i class="el-icon-search" style="margin-right: 5px;"></i>
            <el-input placeholder="请输入昵称" style="width: 200px; margin-right: 10px;" v-model="searchUsername"></el-input>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
        </div>

        <el-table :data="paginatedTableData" style="width: 100%">
          <el-table-column label="序号">
            <template slot-scope="scope">
              {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="date" label="日期"></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="province" label="省份"></el-table-column>
          <el-table-column prop="city" label="市区"></el-table-column>
          <el-table-column prop="address" label="地址" width="260"></el-table-column>
          <el-table-column prop="zip" label="邮编"></el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="showDeleteConfirm(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-sizes="[5, 10]"
            :page-size="pageSize"
            :current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            style="text-align: center; margin-top: 10px;">
        </el-pagination>
      </el-main>
    </el-container>

    <!-- 引入 ContactForm 组件 -->
    <ContactForm ref="contactForm" @refreshList="refreshUserList"/>
  </div>
</template>

<script>
import userList from "@/api/userlist";
import ContactForm from "@/views/userListForm/ContactForm.vue"; // 引入 ContactForm 组件

export default {
  components: {
    ContactForm, // 注册 ContactForm 组件
  },
  data() {
    return {
      allTableData: [],
      total: 0,
      pageSize: 5,
      currentPage: 1,
      searchUsername: "",
    };
  },
  created() {
    this.fetchUserList();
  },
  computed: {
    paginatedTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.allTableData.slice(start, end);
    },
  },
  methods:{
    fetchUserList() {
      userList.getUserList()
        .then((response) => {
          this.allTableData = response.data;
          this.total = this.allTableData.length;
        })
        .catch((error) => {
          this.handleApiError(error, '获取用户列表失败');
        });
    },
    handleSearch() {
      if (this.searchUsername) {
        userList.getUserListByUsername(this.searchUsername)
          .then((response) => {
            this.allTableData = response.data;
            this.total = this.allTableData.length;
          })
          .catch((error) => {
            this.handleApiError(error, '获取用户列表失败');
          });
      } else {
        this.fetchUserList();
      }
    },
    handleEdit(index, row) {
      //console.log("编辑", index, row);
      this.$refs.contactForm.open("编辑联系人", true, row); // 将选中行的数据传递给 ContactForm
    },
    showDeleteConfirm(index, row) {
      this.$confirm('此操作将永久删除该联系人, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(row.id);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleDelete(id) {
      userList.deleteUserList(id)
          .then((response) => {
            this.$message.success('用户信息删除成功');
            this.refreshUserList(); // 刷新用户列表
          })
          .catch((error) => {
            this.handleApiError(error, '用户信息删除失败');
          });
    },
    handleSizeChange(val) {
      //console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.currentPage = 1; // 重置到第一页
    },
    handleCurrentChange(val) {
      //console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
    handleAdd() {
      this.$refs.contactForm.open("新增联系人", false); // 调用 ContactForm 的 open 方法
    },
    refreshUserList() {
      this.fetchUserList(); // 刷新用户列表
    },
    // 处理 API 错误
    handleApiError(error, defaultErrorMessage) {
      if (error.response) {
        // 请求已发出，但服务器响应的状态码不在 2xx 范围内
        const errorMessage = error.response.data || defaultErrorMessage;
        this.$message.error(errorMessage);
      } else if (error.request) {
        // 请求已发出，但没有收到响应
        this.$message.error('请求超时或服务器无响应');
      } else {
        // 在设置请求时发生了一些事情，触发了错误
        this.$message.error(defaultErrorMessage);
      }
    },
  },
};
</script>

<style lang="stylus">
.user-manage-view {
  height: auto;
  background: #ffffff;

  .el-header {
    background-color: #ffffff;
    color: #333;
  }

  .el-main {
    padding: 0;
  }
}
</style>